package com.scaffold.chapter.dao;

import java.util.Collections;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.LogicalExpression;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.ResultTransformer;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import wangjg.commons.page.Page;

import com.scaffold.chapter.entity.Chapter;
import com.scaffold.springmvc.dao.BasicBizDAO;

@Repository
public class ChapterDAO extends BasicBizDAO<Chapter, Long> {
	
	public List<Chapter> findByTopicId(Long topicId) {
		return this.findListByProperty("topicId", topicId);
	}
	
	public List<Chapter> findByCatalogId(Long catalogId) {
		return this.findListByProperty("catalogId", catalogId);
	}

	public List<Chapter> pageQuery(Page page, Long topicId, Long catalogId, String keyword) {
		DetachedCriteria criteria = DetachedCriteria.forClass(this.persistentClass);
		
		this.setColumns(criteria, "id", "title", "catalogId", "imgMap", "created", "modified");
		
		if (catalogId != null) {
			criteria.add(Restrictions.eq("catalogId", catalogId));
		}
		if (topicId != null) {
			criteria.add(Restrictions.eq("topicId", topicId));
		}
		if (keyword != null && !keyword.isEmpty()) {
			LogicalExpression expr = Restrictions.or(
					Restrictions.like("subject", keyword, MatchMode.ANYWHERE),
					Restrictions.like("content", keyword, MatchMode.ANYWHERE));
			criteria.add(expr);
		}
		criteria.addOrder(Order.desc("id"));
		return this.findByCriteria(criteria, page);
	}
	
	protected void setColumns(DetachedCriteria criteria, String...pps){
		ProjectionList pList = Projections.projectionList();
		for(String pp:pps){
			pList.add(Projections.property(pp).as(pp));
		}
		criteria.setProjection(pList);
		criteria.setResultTransformer(Transformers.aliasToBean(Chapter.class));
//		criteria.setResultTransformer(new MyResultTransformer(pps));
	}

	static class MyResultTransformer implements ResultTransformer{
		
		private static final long serialVersionUID = 1L;
		private String[] pps;

		public MyResultTransformer(String[] pps) {
			this.pps = pps;
		}

		public Object transformTuple(Object[] tuple, String[] aliases) {
			for(int i=0;i<tuple.length;i++){
				Object o = tuple[i];
				System.out.print(aliases[i]+"="+o+",");
			}
			System.out.println();
			return tuple[0];
		}
		
		public List transformList(List collection) {
			System.out.println(collection);
			return Collections.emptyList();
		}
		
	}
}
